// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   AbstractConnectionHandler.java

package com.boci.common.handler;

import com.boci.clientapp.main.ClientAppLoader;
import com.boci.common.constant.RequestTypeConst;
import com.boci.common.util.*;
import com.boci.common.vo.ResponseVO;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import sun.misc.BASE64Encoder;
import java.security.*;
import java.security.Security;

// Referenced classes of package com.boci.common.handler:
//            StaticConnectionParam

public abstract class AbstractConnectionHandler
{

    public AbstractConnectionHandler(String pReqType)
        throws Exception
    {
        params = "";
        appConfigurator = ClientAppLoader.getAppConfigurator();
        staticConnectionParam = StaticConnectionParam.getInstance();
        strRequestType = pReqType;
        strRequestURL = staticConnectionParam.getFullURL(strRequestType);
    }

    public void prepareParameters(HashMap pHashMap)
        throws Exception
    {
        StringBuffer sbTmpStr = new StringBuffer();
        String strRequestType = getRequestType();
        String strKey = null;
        String strValue = null;
        Iterator iter = pHashMap.keySet().iterator();
        do
        {
            if(!iter.hasNext())
                break;
            strKey = (String)iter.next();
            strValue = (String)pHashMap.get(strKey);
            sbTmpStr.append(strKey);
            sbTmpStr.append("=");
            sbTmpStr.append(strValue);
            if(iter.hasNext())
                sbTmpStr.append("&");
        } while(true);
        if(!pHashMap.containsKey("encpasswd") && ClientAppLoader.enablePKI() && ClientAppLoader.pki4AllMsg())
        {
            sbTmpStr.append("&");
            sbTmpStr.append("encpasswd");
            sbTmpStr.append("=");
            sbTmpStr.append(StaticConnectionParam.getInstance().getStrEncPass());
        }
        params = sbTmpStr.toString();
    }

    public String send()
        throws Exception
    {
        Logger logger;
        String response;
        HttpURLConnection conn;
        logger = CMLogger.getInstance();
        logger.info((new StringBuilder()).append("Request URL:").append(strRequestURL).toString());
        logger.info((new StringBuilder()).append("Request Parameters:").append(params).toString());
        PerformanceLogger.startConnTimer();
        response = "";
        URL url = null;
        conn = null;

        try{
        	
        	// modify by suddy
        	// don't check the server cer
        	TrustManager tm[] = {new CustomX509TrustManager ()};
        	SSLContext sslContext = SSLContext.getInstance("SSL","SunJSSE");
        	sslContext.init(null, tm, new java.security.SecureRandom());

        	//Get SSLSocketFactory from SSL Context
        	SSLSocketFactory ssf = sslContext.getSocketFactory();
        	
            url = new URL(strRequestURL);        	
	        if("HTTPS".equalsIgnoreCase(url.getProtocol())){
	            conn = (HttpsURLConnection)url.openConnection();
	            ((HttpsURLConnection)conn).setSSLSocketFactory(ssf);
	        }
	        else
	            conn = (HttpURLConnection)url.openConnection();
	        conn.setRequestMethod("POST");
	        conn.setAllowUserInteraction(false);
	        conn.setDoOutput(true);
	        if(!strRequestType.equals(RequestTypeConst.BOCI_LOGIN_URL))
	        {
	            cookies = staticConnectionParam.getStrCookies();
	            conn.setRequestProperty("cookie", cookies);
	        }
	        if(ClientAppLoader.isStandalone() && System.getProperty("https.proxySet") != null && System.getProperty("https.proxySet").equals("true"))
	        {
	            String strAuth = (new StringBuilder()).append(System.getProperty("https.proxyUser")).append(":").append(System.getProperty("https.proxyPassword")).toString();
	            String encodedpswd = (new StringBuilder()).append("Basic ").append((new BASE64Encoder()).encode(strAuth.getBytes())).toString();
	            conn.setRequestProperty("Proxy-Authorization", encodedpswd);
	        }
	        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
	        conn.setRequestProperty("Content-length", Integer.toString(params.length()));
	        writeData(conn, params);
	        response = readResponse(conn);
	        if(strRequestType.equals(RequestTypeConst.BOCI_LOGIN_URL))
	            staticConnectionParam.setStrCookies(saveCookies(conn));
	        if(response != null)
	            response = response.trim();
	    }finally{
	        if(conn != null)
	        {
	            conn.disconnect();
	            conn = null;
	        }
	        PerformanceLogger.stopConnTimer();
	    }
        logger.info((new StringBuilder()).append("Response XML: \n").append(response).toString());
        return response;
    }

    private String saveCookies(URLConnection conn)
    {
        String strCookie = null;
        StringBuffer sbCookie = new StringBuffer();
        int i = 0;
        do
        {
            String headerName = conn.getHeaderFieldKey(i);
            String headerValue = conn.getHeaderField(i);
            if(headerName != null || headerValue != null)
            {
                if("Set-Cookie".equalsIgnoreCase(headerName))
                {
                    if(i > 0)
                        sbCookie.append(";");
                    sbCookie.append(headerValue);
                }
                i++;
            } else
            {
                strCookie = sbCookie.toString();
                return strCookie;
            }
        } while(true);
    }

    private String readResponse(HttpURLConnection conn)
        throws Exception
    {
        String newline = null;
        try
        {
            newline = System.getProperty("line.separator");
        }
        catch(Exception e)
        {
            newline = "\n";
        }
        StringBuffer sb = new StringBuffer();
        InputStream rawInStream = conn.getInputStream();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(rawInStream, "UTF-8"));
        String line;
        while((line = rdr.readLine()) != null) 
            sb.append(line).append(newline);
        rdr.close();
        rawInStream.close();
        return sb.toString();
    }

    private void writeData(HttpURLConnection conn, String data)
        throws Exception
    {
        try
        {
            OutputStream rawOutStream = conn.getOutputStream();
            OutputStreamWriter wout = new OutputStreamWriter(rawOutStream, "UTF-8");
            BufferedWriter writer = new BufferedWriter(wout);
            writer.write(data);
            writer.flush();
            writer.close();
            wout.close();
            rawOutStream.close();
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
        catch(Exception e)
        {
            System.out.println(e);
            e.printStackTrace();
        }
    }

    public String getRequestType()
    {
        return strRequestType;
    }

    public String getRequestURL()
    {
        return strRequestURL;
    }

    protected abstract ResponseVO processResponse(String s)
        throws Exception;

    private String strRequestType;
    private String strRequestURL;
    private String params;
    private String cookies;
    private AppConfigurator appConfigurator;
    private StaticConnectionParam staticConnectionParam;
    private static final String HTTP_TYPE_POST = "POST";
    private static final String ENCODE_UTF8 = "UTF-8";
}
